<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>报表购物系统</title>
    <!-- Bootstrap CSS -->
    <link href="/css/classify/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome 图标 -->
    <link rel="stylesheet" href="/css/classify/all.min.css">
    <style>
        .report-card {
            transition: all 0.3s ease;
            cursor: pointer;
            will-change: transform, box-shadow;
        }

        .report-card:hover {
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }

        .cart-item {
            border-bottom: 1px solid #eee;
            padding: 10px 0;
        }

        .cart-item:last-child {
            border-bottom: none;
        }

        .badge-cart {
            transform: translate(5px, -5px);
        }

        #cartDropdown {
            width: 350px;
            padding: 15px;
        }

        .price {
            color: #e74c3c;
            font-weight: bold;
        }

        #reportList {
            height: 600px;
            overflow-y: auto;
        }

        .loading-spinner {
            display: none;
            text-align: center;
            padding: 20px;
        }

        .selectUserChoose{
            color: white;
        }

        .optionUserChoose{
            color: black;
        }

        /* 用户选择弹窗样式 */
        .user-modal {
            display: none;
            position: fixed;
            z-index: 1050;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
        }

        .user-modal-content {
            background-color: #fefefe;
            margin: 5% auto;
            padding: 20px;
            border: 1px solid #888;
            border-radius: 8px;
            width: 80%;
            max-width: 600px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .user-modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .user-modal-header h3 {
            margin: 0;
            color: #333;
        }

        .user-close {
            color: #aaa;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .user-close:hover {
            color: black;
        }

        .user-modal-body {
            padding: 15px 0;
        }

        .user-modal-footer {
            display: flex;
            justify-content: flex-end;
            padding-top: 15px;
            border-top: 1px solid #eee;
            gap: 10px;
        }

        .user-search-box {
            position: relative;
            margin-bottom: 15px;
        }

        .user-search-box input {
            width: 100%;
            padding: 10px 15px 10px 35px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .user-search-box i {
            position: absolute;
            left: 10px;
            top: 50%;
            transform: translateY(-50%);
            color: #999;
        }

        .user-list-container {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #eee;
            border-radius: 4px;
        }

        .user-item {
            display: flex;
            align-items: center;
            padding: 10px 15px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .user-item:last-child {
            border-bottom: none;
        }

        .user-item:hover {
            background-color: #f9f9f9;
        }

        .user-item.selected {
            background-color: #e6f7ff;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #ddd;
            margin-right: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #666;
            font-weight: bold;
        }

        .user-info {
            flex: 1;
        }

        .user-name {
            font-weight: bold;
            margin-bottom: 3px;
        }

        .user-address {
            font-size: 12px;
            color: #777;
        }

        .user-checkbox {
            margin-left: 10px;
        }
    </style>
</head>
<body>
<!-- 导航栏 -->
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    <div class="container">
        <a class="navbar-brand" th:href="@{/sale}">返回上一页</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav me-auto">
                <li class="nav-item">
                    <a class="nav-link active" href="#">首页</a>
                </li>
                <li class="nav-item">
                    <button class="nav-link selectUserChoose" id="selectUserBtn" style="background: none; border: none;">
                        <span id="selectedUserName">选择客户</span>
                    </button>
                </li>
            </ul>
            <!-- 购物车下拉菜单 -->
            <div class="dropdown">
                <button class="btn btn-outline-light position-relative" type="button" id="cartDropdownBtn"
                        data-bs-toggle="dropdown" aria-expanded="false">
                    <span class="">购物车</span>
                    <span id="cartCount" class="badge bg-danger badge-cart">0</span>
                </button>
                <div class="dropdown-menu dropdown-menu-end" id="cartDropdown" aria-labelledby="cartDropdownBtn">
                    <h5 class="dropdown-header">我的购物车</h5>
                    <div id="cartItems">
                        <div class="text-center py-3">
                            <p>购物车是空的</p>
                        </div>
                    </div>
                    <div class="d-grid gap-2 px-3">
                        <button id="checkoutBtn" class="btn btn-primary" disabled>生成报表</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</nav>

<!-- 主要内容 -->
<div class="container my-5">
    <h2 class="mb-4">选择您需要的产品</h2>

    <!-- 搜索框 -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="input-group">
                <input type="text" class="form-control" placeholder="搜索产品..." id="searchInput">
                <button class="btn btn-outline-secondary" type="button" id="searchBtn">
                    <span>搜索</span>
                </button>
            </div>
        </div>
    </div>

    <!-- 产品列表 -->
    <div class="row" id="reportList">
        <!-- 产品卡片将通过JavaScript动态生成 -->
    </div>
    <div id="loadingSpinner" class="loading-spinner">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
    </div>
</div>

<!-- 结算模态框 -->
<div class="modal fade" id="checkoutModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">确认订单</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <table class="table">
                    <thead>
                    <tr>
                        <th style="display: none">产品Id</th>
                        <th>产品名称</th>
                        <th>单价</th>
                        <th>数量</th>
                        <th>小计</th>
                    </tr>
                    </thead>
                    <tbody id="checkoutItems">
                    <!-- 结算项目将在这里动态生成 -->
                    </tbody>
                    <tfoot>
                    <tr>
                        <th colspan="3">总计</th>
                        <th id="totalAmount">¥0.00</th>
                    </tr>
                    </tfoot>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmCheckout">生成报表</button>
            </div>
        </div>
    </div>
</div>

<!-- 用户选择弹窗 -->
<div id="userModal" class="user-modal">
    <div class="user-modal-content">
        <div class="user-modal-header">
            <h3>选择客户</h3>
            <span class="user-close">&times;</span>
        </div>
        <div class="user-modal-body">
            <div class="user-search-box">
                <input type="text" id="userSearch" placeholder="搜索客户...">
                <i class="fas fa-search"></i>
            </div>
            <div class="user-list-container" id="userList">
                <!-- 用户列表将通过JavaScript动态生成 -->
            </div>
        </div>
        <div class="user-modal-footer">
            <button id="confirmUserBtn" class="btn btn-primary">确认选择</button>
            <button id="cancelUserBtn" class="btn btn-secondary">取消</button>
        </div>
    </div>
</div>

<!-- 在 <head> 标签内或 <body> 开始处加载 jQuery -->
<script src="/js/classify/jquery-3.6.0.min.js"></script>

<!-- 延迟加载非关键JS -->
<script src="/js/classify/bootstrap.bundle.min.js" defer></script>

<script th:inline="javascript">
    // 将服务端的 products 转为 JS 变量
    const serverProducts = [[${products}]];

    const userList = [[${userList}]];

    // 编辑所用到的元素
    const editUser = [[${user}]];

    const saleProductsList = [[${saleProductsList}]];

    const saleId = [[${saleId}]];
</script>

<script>
    // 模拟产品数据
    const reports = [];

    // 购物车数据 - 优化后的结构
    let cart = {
        items: [],
        lookup: {} // 用于快速查找
    };

    // 分页和虚拟滚动变量
    let visibleItems = 12;
    let currentIndex = 0;
    let isLoading = false;

    // 缓存常用DOM元素
    const $reportList = $('#reportList');
    const $cartCount = $('#cartCount');
    const $cartItems = $('#cartItems');
    const $checkoutBtn = $('#checkoutBtn');
    const $loadingSpinner = $('#loadingSpinner');
    const $searchInput = $('#searchInput');

    // 用户相关变量
    let selectedUser = null;
    let users = [];

    // 初始化页面
    $(document).ready(function () {
        // 初始化数据
        const data = serverProducts;
        for (let dataKey in data) {
            reports.push(data[dataKey]);
        }

        // 初始加载
        loadMoreItems();

        // 从本地存储加载购物车
        if (saleProductsList !== null){
            // 加载购物车项
            saleProductsList.forEach(item => {
                // 兼容新旧格式
                const itemId = item.products.id;
                const quantity = parseInt(item.number);

                const report = reports.find(r => r.id === itemId);
                if (report) {
                    const cartItem = {
                        id: report.id,
                        name: report.name,
                        price: report.price,
                        quantity: quantity
                    };
                    cart.items.push(cartItem);
                    cart.lookup[report.id] = cartItem;
                }
            });
        } else {
            loadCartFromStorage();
        }

        updateCartUI();

        // 初始化用户数据
        initUserData();

        // 事件委托绑定
        $reportList.on('click', '.add-to-cart', function () {
            const reportId = $(this).data('id');
            addToCart(reportId);
        });

        // 搜索功能 - 添加防抖
        let searchTimeout;
        $searchInput.on('input', function () {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(searchReports, 300);
        });

        $('#searchBtn').click(searchReports);

        // 结算按钮点击事件
        $checkoutBtn.click(showCheckoutModal);

        // 确认支付按钮点击事件
        $('#confirmCheckout').click(confirmCheckout);

        // 滚动加载更多 - 添加节流
        let isScrolling;
        $reportList.on('scroll', function () {
            clearTimeout(isScrolling);
            isScrolling = setTimeout(() => {
                if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight - 100) {
                    loadMoreItems();
                }
            }, 100);
        });

        // 用户选择相关事件
        $('#selectUserBtn').click(openUserModal);
        $('.user-close, #cancelUserBtn').click(closeUserModal);
        $('#confirmUserBtn').click(confirmUserSelection);
        $('#userSearch').on('input', filterUsers);
    });

    // 初始化用户数据
    function initUserData() {
        // 先进行判断，通过判断来确定当前是处于增加还是编辑
        if (editUser !== null) {
            // 如果 editUser 不为空，说明是编辑
            users.push(editUser);
        } else {
            users = Array.isArray(userList) ? userList : [];
        }

        if (users.length === 0) {
            // 如果后端数据库没有数据则返回错误
            window.alert('客户列表中没有客户，请先添加客户');
            window.location.href = '/user';
            return;
        }

        // 默认选择第一个用户
        selectedUser = users[0];
        $('#selectedUserName').text('请选择客户');

        // 渲染用户列表
        renderUserList(users);
    }

    // 打开用户选择弹窗
    function openUserModal() {
        $('#userModal').show();
    }

    // 关闭用户选择弹窗
    function closeUserModal() {
        $('#userModal').hide();
    }

    let userId = 0;

    // 确认用户选择
    function confirmUserSelection() {
        const selected = $('.user-item.selected');
        if (selected.length > 0) {
            userId = selected.data('id');
            selectedUser = users.find(user => user.id === userId);
            $('#selectedUserName').text(selectedUser.name);
            closeUserModal();
        } else {
            alert('请先选择一个客户');
        }
    }

    // 过滤用户
    function filterUsers() {
        const keyword = $('#userSearch').val().toLowerCase();
        const filtered = users.filter(user =>
            user.name.toLowerCase().includes(keyword) ||
            (user.email && user.email.toLowerCase().includes(keyword))
        );
        renderUserList(filtered);
    }

    // 渲染用户列表
    function renderUserList(usersToRender) {
        const $userList = $('#userList');
        $userList.empty();

        usersToRender.forEach(user => {
            const $userItem = $(`
                <div class="user-item" data-id="${user.id}">
                    <div class="user-avatar">${user.name.charAt(0)}</div>
                    <div class="user-info">
                        <div class="user-name">${user.name}</div>
                        ${user.mobile ? `<div class="user-address">手机号码： ${user.mobile}</div>` : ''}
                        ${user.address ? `<div class="user-address">施工地址： ${user.address}</div>` : ''}
                    </div>
                    <input type="radio" name="selectedUser" class="user-checkbox"
                           ${selectedUser && selectedUser.id === user.id ? 'checked' : ''}>
                </div>
            `);

            $userItem.click(function() {
                $('.user-item').removeClass('selected');
                $(this).addClass('selected');
                $('.user-checkbox').prop('checked', false);
                $(this).find('.user-checkbox').prop('checked', true);
            });

            if (selectedUser && selectedUser.id === user.id) {
                $userItem.addClass('selected');
            }

            $userList.append($userItem);
        });
    }

    // 加载更多产品项
    function loadMoreItems() {
        if (isLoading) return;

        $loadingSpinner.show();
        isLoading = true;

        // 模拟异步加载
        setTimeout(() => {
            const itemsToRender = reports.slice(currentIndex, currentIndex + visibleItems);
            renderReportList(itemsToRender);
            currentIndex += visibleItems;

            $loadingSpinner.hide();
            isLoading = false;

            // 如果还有更多数据，可以继续加载
            if (currentIndex < reports.length) {
                loadMoreItems();
            }
        }, 300);
    }

    // 渲染产品列表 - 使用文档片段
    function renderReportList(reportsToRender) {
        const fragment = document.createDocumentFragment();

        reportsToRender.forEach(report => {
            let model = report.model;
            const card = document.createElement('div');
            card.className = 'col-md-4 mb-4';
            card.innerHTML = `
                <div class="card report-card h-100" data-id="${report.id}">
                    <div class="card-body">
                        <h5 class="card-title">${report.name}</h5>
                        <span>${model.size}</span>
                        <span style="color: #a8a8a8">|</span>
                        <span>${model.thickness}</span>
                        <div class="d-flex justify-content-between align-items-center">
                            <span class="price">¥${Number(report.price).toFixed(2)}</span>
                            <button class="btn btn-sm btn-outline-primary add-to-cart" data-id="${report.id}">
                                加入购物车
                            </button>
                        </div>
                    </div>
                    <div class="card-footer bg-transparent">
                        <small class="text-muted">${report.address}</small>
                    </div>
                </div>
            `;
            fragment.appendChild(card);
        });

        $reportList.append(fragment);
    }

    // 添加到购物车 - 使用优化后的数据结构
    function addToCart(reportId) {
        if (cart.lookup[reportId]) {
            cart.lookup[reportId].quantity += 1;
        } else {
            const report = reports.find(r => r.id === reportId);

            if (!report) return;

            const newItem = {
                id: report.id,
                modelId: report.model.id,
                name: report.name,
                price: report.price,
                quantity: 1
            };
            cart.items.push(newItem);
            cart.lookup[reportId] = newItem;
        }

        updateCartUI();
        saveCartToStorage();
        showToast(`${cart.lookup[reportId].name} 已添加到购物车`);
    }

    // 更新购物车UI
    function updateCartUI() {
        // 更新购物车数量
        const totalItems = cart.items.reduce((sum, item) => sum + item.quantity, 0);
        $cartCount.text(totalItems);

        // 更新购物车下拉菜单内容
        $cartItems.empty();

        if (cart.items.length === 0) {
            $cartItems.append('<div class="text-center py-3"><p>购物车是空的</p></div>');
            $checkoutBtn.prop('disabled', true);
        } else {
            cart.items.forEach(item => {
                const cartItem = `
                    <div class="cart-item">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h6 class="mb-1">${item.name}</h6>
                                <small>¥${Number(item.price).toFixed(2)} × ${item.quantity}</small>
                            </div>
                            <div>
                                <span class="text-danger">¥${(item.price * item.quantity).toFixed(2)}</span>
                                <button class="btn btn-sm btn-outline-danger remove-item" data-id="${item.id}">
                                    <span>X</span>
                                </button>
                            </div>
                        </div>
                    </div>
                `;
                $cartItems.append(cartItem);
            });

            // 计算总价
            const total = cart.items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
            $cartItems.append(`<div class="text-end mt-2"><strong>合计: ¥${total.toFixed(2)}</strong></div>`);

            $checkoutBtn.prop('disabled', false);

            // 添加删除按钮事件 - 使用事件委托
            $cartItems.on('click', '.remove-item', function () {
                const itemId = $(this).data('id');
                removeFromCart(itemId);
            });
        }
    }

    // 从购物车移除项目
    function removeFromCart(reportId) {
        const itemIndex = cart.items.findIndex(item => item.id === reportId);
        if (itemIndex !== -1) {
            cart.items.splice(itemIndex, 1);
            delete cart.lookup[reportId];
            updateCartUI();
            saveCartToStorage();
        }
    }

    // 保存购物车到本地存储 - 使用节流和简化结构
    let saveCartTimeout;

    function saveCartToStorage() {
        clearTimeout(saveCartTimeout);
        saveCartTimeout = setTimeout(() => {
            const simplifiedCart = {
                items: cart.items.map(item => ({
                    id: item.id,
                    q: item.quantity
                }))
            };
            localStorage.setItem('reportCart', JSON.stringify(simplifiedCart));
        }, 500);
    }

    // 显示结算模态框
    function showCheckoutModal() {
        const $checkoutItems = $('#checkoutItems');
        $checkoutItems.empty();

        cart.items.forEach(item => {
            const row = `
                <tr>
                    <td style="display: none">${String(item.id)}</td>
                    <td>${item.name}</td>
                    <td>¥${Number(item.price).toFixed(2)}</td>
                    <td>${item.quantity}</td>
                    <td>¥${(item.price * item.quantity).toFixed(2)}</td>
                </tr>
            `;
            $checkoutItems.append(row);
        });

        // 计算总价
        const total = cart.items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
        $('#totalAmount').text(`¥${total.toFixed(2)}`);

        // 显示模态框
        const checkoutModal = new bootstrap.Modal(document.getElementById('checkoutModal'));
        checkoutModal.show();
    }

    // 结算确认函数
    async function confirmCheckout() {
        if (!selectedUser) {
            alert('请先选择客户');
            return;
        }

        try {
            // 1. 准备数据
            const orderData = {
                saleProducts: cart.items.map(item => ({
                    productId: item.id,// 产品编号
                    unitPrice: item.price * item.quantity,// 每个销售产品的总价
                    quantity: item.quantity// 数量
                })),
                userId: userId,
                totalAmount: calculateTotalAmount(), // 计算总金额的函数
                saleId: saleId
            };

            // 2. 显示加载状态
            $('#confirmCheckout').prop('disabled', true).html(
                '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 处理中...'
            );

            // 3. 发送请求
            const response = await submitOrderToBackend(orderData);

            console.log(response)
            console.log("response.success = "  + response.success)

            // 4. 处理响应
            if (response) {
                // 清空购物车
                cart = {items: [], lookup: {}};
                updateCartUI();
                saveCartToStorage();

                // 显示成功消息
                showToast('订单提交成功！', 'success');

                // 关闭模态框
                $('#checkoutModal').modal('hide');

                // 可选：跳转到订单详情页
                window.location.href = '../sale';
            } else {
                showToast(`提交失败: ${response.message}`, 'error');
            }
        } catch (error) {
            console.error('订单提交错误:', error);
            showToast('提交订单时出错，请重试', 'error');
        } finally {
            // 恢复按钮状态
            $('#confirmCheckout').prop('disabled', false).text('确认支付');
        }
    }

    // 计算总金额
    function calculateTotalAmount() {
        return cart.items.reduce((total, item) => total + (item.price * item.quantity), 0);
    }

    // 发送订单到后端
    async function submitOrderToBackend(orderData) {
        try {
            const response = await fetch('/sale/save-saleProducts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    // 如果需要认证，添加认证头
                    'Authorization': `Bearer ${getAuthToken()}`
                },
                body: JSON.stringify(orderData)
            });

            if (!(response.status === 200)) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            return response.url;
        } catch (error) {
            console.error('提交订单错误:', error);
            throw error;
        }
    }

    // 获取认证token的函数示例
    function getAuthToken() {
        // 从cookie或localStorage获取token
        return localStorage.getItem('authToken') || '';
    }

    // 搜索产品
    function searchReports() {
        const keyword = $searchInput.val().toLowerCase().trim();

        if (!keyword) {
            currentIndex = 0;
            $reportList.empty();
            loadMoreItems();
            return;
        }

        const filteredReports = reports.filter(report =>
            report.name.toLowerCase().includes(keyword) ||
            (report.description && report.description.toLowerCase().includes(keyword)) ||
            (report.category && report.category.toLowerCase().includes(keyword))
        );

        currentIndex = 0;
        $reportList.empty();

        // 显示筛选结果
        const fragment = document.createDocumentFragment();
        filteredReports.forEach(report => {
            let model = report.model;
            const card = document.createElement('div');
            card.className = 'col-md-4 mb-4';
            card.innerHTML = `
                <div class="card report-card h-100" data-id="${report.id}">
                    <div class="card-body">
                        <h5 class="card-title">${report.name}</h5>
                        <span>${model.size}</span>
                        <span style="color: #a8a8a8">|</span>
                        <span>${model.thickness}</span>
                        <div class="d-flex justify-content-between align-items-center">
                            <span class="price">¥${Number(report.price).toFixed(2)}</span>
                            <button class="btn btn-sm btn-outline-primary add-to-cart" data-id="${report.id}">
                                <i class="fas fa-cart-plus"></i> 加入购物车
                            </button>
                        </div>
                    </div>
                    <div class="card-footer bg-transparent">
                        <small class="text-muted">${report.address}</small>
                    </div>
                </div>
            `;
            fragment.appendChild(card);
        });

        $reportList.append(fragment);
    }

    // 从本地存储加载购物车
    function loadCartFromStorage() {
        try {
            const savedCart = localStorage.getItem('reportCart');

            // 初始化空购物车
            cart = {items: [], lookup: {}};

            if (!savedCart) return;

            const parsedCart = JSON.parse(savedCart);

            // 验证数据格式
            if (!parsedCart || !parsedCart.items || !Array.isArray(parsedCart.items)) {
                console.warn("无效的购物车数据格式，重置购物车");
                localStorage.removeItem('reportCart');
                return;
            }

            // 确保产品数据已加载
            if (!reports || reports.length === 0) {
                console.warn("产品数据未加载，无法恢复购物车");
                return;
            }

            // 加载购物车项
            parsedCart.items.forEach(item => {
                // 兼容新旧格式
                const itemId = item.id;
                const quantity = item.q || item.quantity || 1;

                const report = reports.find(r => r.id === itemId);
                if (report) {
                    const cartItem = {
                        id: report.id,
                        name: report.name,
                        price: report.price,
                        quantity: quantity
                    };
                    cart.items.push(cartItem);
                    cart.lookup[report.id] = cartItem;
                }
            });

            console.log("购物车从本地存储恢复成功", cart);
        } catch (error) {
            console.error("加载购物车失败:", error);
            // 恢复失败时重置购物车
            cart = {items: [], lookup: {}};
            localStorage.removeItem('reportCart');
        }
    }

    // 显示提示消息
    function showToast(message, type = 'info') {
        // 实际项目中可以使用更完善的toast组件
        const toast = document.createElement('div');
        toast.className = `toast show position-fixed bottom-0 end-0 mb-3 me-3 bg-${type === 'success' ? 'success' : 'info'}`;
        toast.style.zIndex = '9999';
        toast.innerHTML = `
            <div class="toast-body text-white">
                <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-info-circle'} me-2"></i>
                ${message}
            </div>
        `;
        document.body.appendChild(toast);

        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }
</script>
</body>
</html>